package com.health.activity.print;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

import com.health.NovaActivity;
import com.health.NovaApplication;
import com.health.R;
import com.health.tablebean.ARCHIVE_BASEINFO;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import net.yt.android.util.bluetoothprinter.SNBCCommond;

/**
 * 打印条码
 * 
 * @author 鹿云龙
 */
public class PrintActivity extends NovaActivity {
	private final String NOCONNECT = "设备未连接";
	private final String PAPERISOUT = "he paper is out";
	private final String COVERISOPEN = "the cover is open ";

	private ARCHIVE_BASEINFO userInfo;// 基本信息

	private BluetoothReciever mbluetoothReceive;

	private SNBCCommond sdkcmd = null;

	boolean bConncet = false;
	private static final int LBWIDTH = 600;
	private static final int LBHEIGHT = 400;

	@Override
	protected void onDestroy() {

		try {
			// adapter.enable()disable();
			if (sdkcmd != null) {
				sdkcmd.disconnect();
			}
			// registerReceiver(mbluetoothReceive, intentFilter);
			unregisterReceiver(mbluetoothReceive);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.onDestroy();
	}

	private ArrayList<String> address = new ArrayList<String>();
	BluetoothAdapter adapter;
	private Button btn_back;
	private Button btn_up;
	String straddRess;

	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try {
			setContentView(R.layout.activity_print);
			btn_back = (Button) findViewById(R.id.btn_back);
			btn_up = (Button) findViewById(R.id.btn_up);
			userInfo = NovaApplication.getUserInfo();

			btn_back.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					finish();
				}
			});
			btn_up.setVisibility(View.GONE);

			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
					.detectNetwork().penaltyLog().build());

			StrictMode.setVmPolicy(
					new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath().build());

			// 获取已配对的蓝牙设备----
			// address.clear();
			// BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
			// Set<BluetoothDevice> devices = adapter.getBondedDevices();
			// for (int i = 0; i < devices.size(); i++) {
			// BluetoothDevice device = (BluetoothDevice)
			// devices.iterator().next();
			// System.out.println(device.getName());
			// if (device.getName().equals("BTP-P33")) {
			// address.add(device.getAddress());
			// }
			// }
			// adapter.disable();
			// adapter.enable();
			adapter = BluetoothAdapter.getDefaultAdapter();
			// 获得已配对的远程蓝牙设备的集合
			Set<BluetoothDevice> bondevices = adapter.getBondedDevices();
			if (bondevices.size() > 0) {
				for (Iterator<BluetoothDevice> it = bondevices.iterator(); it.hasNext();) {
					BluetoothDevice bondevice = (BluetoothDevice) it.next();
					// 打印出远程蓝牙设备的物理地址
					String bonname = bondevice.getName();
					if (bonname.equals("BTP-P33")) {
						straddRess = bondevice.getAddress();
						System.out.println(bondevice.getAddress());
					}
				}
			} else {
				System.out.println("还没有已配对的远程蓝牙设备！");
			}
			//////////////////////////////
			address.clear();
			BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
			Set<BluetoothDevice> devices = adapter.getBondedDevices();
			for (int i = 0; i < devices.size(); i++) {
				BluetoothDevice device = (BluetoothDevice) devices.iterator().next();
				System.out.println(device.getName());
				device.getType();
				if (device.getName().equals("BTP-P33")) {
					address.add(device.getAddress());
				}
			}
			// ----------------------

			// 注册蓝牙服务
			IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
			mbluetoothReceive = new BluetoothReciever();
			registerReceiver(mbluetoothReceive, intentFilter);
			// sendBroadcast(intent);
			// 设置广播信息过滤
			// 注册广播接收器，接收并处理搜索结果
			// 寻找蓝牙设备，android会将查找到的设备以广播形式发出去
			adapter.startDiscovery();
			findViews();
			setListeners();

			// -------------

			// -------------
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	TextView title;

	@Override
	public void findViews() {
		// gd_menu = (GridView) findViewById(R.id.gd_menu);
		// menuAdapter = new RecordFileGridAdapter(getApplicationContext());
		// gd_menu.setAdapter(menuAdapter);
		title = (TextView) findViewById(R.id.title);
		title.setText("打印条码");
	}

	@Override
	public void setListeners() {
		try {
			// 创建连接
			TextView btnConnect = (TextView) findViewById(R.id.btn_lianjieshebei);
			btnConnect.setOnClickListener(new ConnectListener());
			// 创建连接
			TextView btnPrintTiaoMa = (TextView) findViewById(R.id.btn_dayinjiankangbaogao);
			btnPrintTiaoMa.setOnClickListener(new PrintBarcodeListener());
			// // 断开连接
			// Button btnDISConnect = (Button)
			// findViewById(R.id.btndisconnect_blue);
			// btnDISConnect.setOnClickListener(new DISConnectListener());

			// // 获取打印机状态
			// Button btnQeuryStatus = (Button)
			// findViewById(R.id.btnQueryStatus_blue);
			// btnQeuryStatus.setOnClickListener(new QueryStatusListener());

			// // 打印文本
			// Button btnPrintText = (Button)
			// findViewById(R.id.btnprinttext_blue);
			// btnPrintText.setOnClickListener(new PrintTextListener());

			// // 打印直线
			// Button btnPrintLine = (Button)
			// findViewById(R.id.btnprintline_blue);
			// btnPrintLine.setOnClickListener(new PrintLineistener());

			// // 打印一维条码
			// Button btnPrintBarcode = (Button)
			// findViewById(R.id.btnprintbarcode_blue);
			// btnPrintBarcode.setOnClickListener(new PrintBarcodeListener());

			// // 打印QR码
			// Button btnPrintQRCode = (Button)
			// findViewById(R.id.btnprintqrcode_blue);
			// btnPrintQRCode.setOnClickListener(new PrintQRCodeListener());

			// // 打印图片
			// Button btnPrintPicture = (Button)
			// findViewById(R.id.btnprintpicture_blue);
			// btnPrintPicture.setOnClickListener(new PrintPictureListener());

			// // 定位到标签
			// Button btnFeed = (Button) findViewById(R.id.btnfeed_blue);
			// btnFeed.setOnClickListener(new FeedListener());
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 创建连接
	private class ConnectListener implements OnClickListener {

		@Override
		public void onClick(View v) {

			try {
				if (!checkBluetooth()) {
					showTextDialog("请先绑定设备");
					return;
				}
				if (straddRess == null || straddRess.equals("")) {
					showTextDialog("请先绑定设备");
					return;
				}

				if (bConncet == false) {
					showTextDialog("正在连接设备...");
					// 建立连接
					// String strMac = "8C:DE:52:BF:CA:86";
					// String strMac = "00:12:6F:35:EF:CB";
					// if (address.size() > 0) {
					// strMac = address.get(0);
					// } else {
					// // 搜索设备
					// }
					// 00:12:6F:35:EF:CB
					// 创建内部类
					sdkcmd = new SNBCCommond();
					sdkcmd.connect(straddRess);

					if (sdkcmd.isConnected()) {
						bConncet = true;
						// Toast.makeText(PrintActivity.this, "连接成功",
						// Toast.LENGTH_SHORT).show();
					} else {
						// Toast.makeText(PrintActivity.this, "连接失败",
						// Toast.LENGTH_SHORT).show();
						showTextDialog("连接失败");
					}
					// mHandler.sendEmptyMessage(0);

				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				// do something,refresh UI;
				System.out.println("connect");
				System.out.println("connect");
				sdkcmd = new SNBCCommond();
				sdkcmd.connect(straddRess);
				if (sdkcmd.isConnected()) {
					bConncet = true;
					// Toast.makeText(PrintActivity.this, "连接成功",
					// Toast.LENGTH_SHORT).show();
					showTextDialog("连接成功");
				} else {
					showTextDialog("连接失败");
					// Toast.makeText(PrintActivity.this, "连接失败",
					// Toast.LENGTH_SHORT).show();
				}
				break;
			default:
				break;
			}
		}

	};
	// // 断开连接
	// private class DISConnectListener implements OnClickListener {
	// @Override
	// public void onClick(View v) {
	// if (!checkBluetooth()) {
	// return;
	// }
	// if (bConncet == true) {
	// sdkcmd.disconnect();
	// sdkcmd = null;
	// bConncet = false;
	// Toast.makeText(PrintActivity.this, "DisConnect Success",
	// Toast.LENGTH_SHORT).show();
	// }
	// }
	// }

	// // 获取打印机状态
	// private class QueryStatusListener implements OnClickListener {
	//
	// @Override
	// public void onClick(View v) {
	//
	// if (!checkBluetooth()) {
	// return;
	// }
	// if (bConncet == false) {
	// Toast.makeText(PrintActivity.this, NOCONNECT, Toast.LENGTH_SHORT).show();
	// return;
	// }
	// String error_str = sdkcmd.printerStatus();
	// if (error_str.equals("1")) {
	// Toast.makeText(PrintActivity.this, PAPERISOUT,
	// Toast.LENGTH_SHORT).show();
	// } else if (error_str.equals("2")) {
	// Toast.makeText(PrintActivity.this, COVERISOPEN,
	// Toast.LENGTH_SHORT).show();
	// } else if (error_str.equals("0")) {
	// Toast.makeText(PrintActivity.this, "Ready To Print",
	// Toast.LENGTH_SHORT).show();
	// }
	//
	// }
	// }

	// // 打印文本
	// private class PrintTextListener implements OnClickListener {
	//
	// @Override
	// public void onClick(View v) {
	//
	// if (!checkBluetooth()) {
	// return;
	// }
	// if (bConncet == false) {
	// Toast.makeText(PrintActivity.this, NOCONNECT, Toast.LENGTH_SHORT).show();
	// return;
	// }
	// // 打印文本
	// // sdkcmd.pageSetup(LBWIDTH, LBHEIGHT);
	// // 打印边框
	// // sdkcmd.drawBox(2, 0, 0, 200, 200);
	// // 可以通过fontSize设置字体大小，取值范围为1~7
	// String str = "可以通过fontSize设置字体大小，取值范围为1~7";
	// sdkcmd.drawText(10, 10, str, 1, 0, 0, false, false);
	// // int rotate, int bold, boolean reverse, boolean underline)
	// // 旋转角度，加粗，反转，下划线
	// // sdkcmd.draw
	// // sdkcmd.drawText(10, 20, "Hello 新北洋", 2, 0, 0, false, false);
	// // sdkcmd.drawText(10, 35, "Hello 新北洋", 3, 0, 0, false, false);
	// // sdkcmd.drawText(10, 55, "Hello 新北洋", 4, 0, 0, false, false);
	// // sdkcmd.drawText(10, 85, "Hello 新北洋", 5, 0, 0, false, false);
	// // sdkcmd.drawText(10, 120, "Hello 新北洋", 6, 0, 0, false, false);
	// // sdkcmd.drawText(10, 160, "Hello 新北洋", 7, 0, 0, false, false);
	// // sdkcmd.
	// // sdkcmd.print(1, 1);
	// }
	// }

	// public void printHealth() {
	//
	// }
	// // 打印直线
	// private class PrintLineistener implements OnClickListener {
	//
	// @Override
	// public void onClick(View v) {
	// if (!checkBluetooth()) {
	// return;
	// }
	// if (bConncet == false) {
	// Toast.makeText(PrintActivity.this, NOCONNECT, Toast.LENGTH_SHORT).show();
	// return;
	// }
	// sdkcmd.pageSetup(LBWIDTH, LBHEIGHT);
	// sdkcmd.drawLine(3, 10, 5, 400, 5, false);
	// sdkcmd.drawLine(3, 10, 25, 10, 200, true);
	// sdkcmd.print(0, 1);
	// }
	// }

	// 打印一维条码
	private class PrintBarcodeListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			try {
				if (!checkBluetooth()) {
					return;
				}
				if (bConncet == false) {
					showTextDialog(NOCONNECT);
					return;
				}

				sdkcmd.pageSetup(LBWIDTH, LBHEIGHT);
				sdkcmd.drawBarCode(10, 10, userInfo.getIDCARD(), 1, 0, 5, 30);
				sdkcmd.print(0, 1);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	// // 打印QR码
	// private class PrintQRCodeListener implements OnClickListener {
	//
	// @Override
	// public void onClick(View v) {
	//
	// if (!checkBluetooth()) {
	// return;
	// }
	// if (bConncet == false) {
	// Toast.makeText(PrintActivity.this, NOCONNECT, Toast.LENGTH_SHORT).show();
	// return;
	// }
	// sdkcmd.pageSetup(LBWIDTH, LBHEIGHT);
	// sdkcmd.drawQrCode(5, 5, "123456789", 0, 5, 0);
	// sdkcmd.print(0, 1);
	//
	// }
	// }

	// private class PrintPictureListener implements OnClickListener {
	//
	// @Override
	// public void onClick(View v) {
	// if (!checkBluetooth()) {
	// return;
	// }
	// if (bConncet == false) {
	// Toast.makeText(PrintActivity.this, NOCONNECT, Toast.LENGTH_SHORT).show();
	// return;
	// }
	// // sdkcmd.pageSetup(LBWIDTH, LBHEIGHT);
	//
	// FileInputStream temp_stream = null;
	// Bitmap image;
	//
	// String img_name = Environment.getExternalStorageDirectory() +
	// "/Lion.JPG";
	// try {
	// System.out.println(img_name);
	// temp_stream = new FileInputStream(img_name);
	// } catch (FileNotFoundException e) {
	// e.printStackTrace();
	// }
	//
	// if (temp_stream == null) {
	// Toast.makeText(PrintActivity.this, "Read Image Fail",
	// Toast.LENGTH_SHORT).show();
	// return;
	// }
	// image = BitmapFactory.decodeStream(temp_stream);
	// sdkcmd.drawGraphic(10, 10, 0, 0, image);
	// sdkcmd.print(0, 1);
	// }
	// }

	// private class FeedListener implements OnClickListener {
	//
	// @Override
	// public void onClick(View v) {
	// if (!checkBluetooth()) {
	// return;
	// }
	//
	// if (bConncet == false) {
	// Toast.makeText(PrintActivity.this, NOCONNECT, Toast.LENGTH_SHORT).show();
	// return;
	// }
	// sdkcmd.feed();
	// }
	// }

	/**
	 * 设备查找类
	 * 
	 * @author 鹿云龙
	 */
	public class BluetoothReciever extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			try {
				System.out.println("onReceive------------------------------------");
				String action = intent.getAction();
				try {
					if (BluetoothDevice.ACTION_FOUND.equals(action)) {
						BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
						Log.i("Bluetooth", "Found:" + device.getName());
						// BTP-P33
						String name = device.getName();
						System.out.println(name);
						if (name != null) {
							if (device.getName().equals("BTP-P33")) {
								if (straddRess == null || straddRess.equals("")) {
									straddRess = device.getAddress();
								}
							}
						}

						// for (String str : address) {
						// if (device.equals(str)) {
						// straddRess = device.getAddress();
						// return;
						// }
						// }
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 检查是否开启蓝牙，设备是否绑定
	 * 
	 * @return 有绑定的设备后返回true，蓝牙未开启或没有绑定设备返回false
	 * @author 鹿云龙
	 * @date 2015年10月24日 上午11:48:38
	 */
	public boolean checkBluetooth() {
		try {
			BluetoothAdapter blueadapter = BluetoothAdapter.getDefaultAdapter();

			if (!blueadapter.isEnabled()) {// 是否开启蓝牙
				Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableBtIntent, 1);
				return false;
			}
			// else {
			// String error_str = sdkcmd.printerStatus();
			// if (error_str.equals("1")) {
			// Toast.makeText(PrintActivity.this, PAPERISOUT,
			// Toast.LENGTH_SHORT).show();
			// return false;
			// } else if (error_str.equals("2")) {
			// Toast.makeText(PrintActivity.this, COVERISOPEN,
			// Toast.LENGTH_SHORT).show();
			// return false;
			// } else if (error_str.equals("0")) {
			// System.out.println("准备打印------------------------------------");
			// // Toast.makeText(PrintActivity.this, "Ready To Print",
			// // Toast.LENGTH_SHORT).show();
			// }
			// }
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}
}